use std::{collections::BTreeMap, num::NonZero};

pub struct Palette<T> {
    pub indices: Vec<usize>,
    pub values: Vec<Option<T>>,
}

impl<T> Default for Palette<T> {
    fn default() -> Self {
        Self {
            indices: Vec::default(),
            values: vec![None],
        }
    }
}

impl<T> Palette<T> {
    pub fn new(len: usize) -> Self {
        Self {
            indices: vec![0; len],
            ..Default::default()
        }
    }
}

impl<T> Palette<T>
where
    T: PartialEq,
{
    pub fn set(&mut self, position: usize, value: T) {
        if let Some(index) = self.indices.get_mut(position) {
            *index = self
                .values
                .iter()
                .enumerate()
                .find(|(_, opt_v)| matches!(opt_v, Some(v) if *v == value))
                .map(|x| x.0)
                .unwrap_or_else(|| {
                    let index = self.values.len();
                    self.values.push(Some(value));
                    index
                });
        }
    }

    pub fn get(&self, position: usize) -> Option<&T> {
        self.indices
            .get(position)
            .and_then(|x| self.values.get(*x))
            .and_then(|x| x.as_ref())
    }

    pub fn remove(&mut self, position: usize) {
        self.indices[position] = 0;
    }

    pub fn compact(&mut self) {
        let mut unused: BTreeMap<_, _> = (0..self.values.len()).map(|i| (i, i)).collect();
        for i in 0..self.indices.len() {
            unused.remove(&self.indices[i]);
        }

        for (old, new) in unused.iter_mut().rev() {
            *new = self.values.len();
            self.values.swap_remove(*old);
        }

        unused.retain(|old, new| old != new);

        for idx in self.indices.iter_mut() {
            if let Some((old, _)) = unused.iter().find(|x| x.1 == idx) {
                *idx = *old
            }
        }
    }

    pub fn is_empty(&mut self, position: usize) -> bool {
        self.indices[position] == 0
    }

    pub fn iter(&self) -> impl Iterator<Item = &Option<T>> {
        self.indices.iter().flat_map(|x| self.values.get(*x))
    }

    pub fn get_value(&self, idx: NonZero<usize>) -> &T {
        self.values[idx.get()].as_ref().unwrap()
    }
}

#[cfg(test)]
mod test {
    use crate::Palette;

    #[test]
    pub fn set_value() {
        let mut p: Palette<String> = Palette::default();

        p.set(3, "value".into());
        p.set(5, "value".into());

        p.set(8, "bar".into());

        let snapshot = p.iter().collect::<Vec<_>>();

        assert_eq!(p.values.len(), 3);
        assert!(matches!(snapshot[3], Some(s) if s == "value"));
        assert!(matches!(snapshot[5], Some(s) if s == "value"));

        println!("{:?}", p.values)
    }

    #[test]
    pub fn remove_value() {
        let mut p: Palette<String> = Palette::default();
        p.set(3, "value".into());
        p.set(5, "value".into());

        p.set(8, "bar".into());
        p.set(9, "foo".into());
        println!("{:?}", p.iter().collect::<Vec<_>>());
        p.remove(8);
        p.remove(9);

        assert_eq!(p.values.len(), 4);
        println!("{:?}", p.values);
        println!("{:?}", p.iter().collect::<Vec<_>>());

        p.compact();
        assert_eq!(p.values.len(), 2);
        println!("{:?}", p.values);
        println!("{:?}", p.iter().collect::<Vec<_>>());
    }
}
